<template>
    <div>

        <el-button type="primary" class="mb-3" @click="navigateToSrc">新标签页观看</el-button>

        <div class="page-navigation fixed-navigation">
            <input v-model="gotoPageNum" @keyup.enter="goToPage" type="number" min="1" :max="totalPages" />

            <span>/ {{ totalPages }}</span>
            <el-button @click="printPdf">打印 PDF</el-button>
        </div>
        <div ref="pdfCanvasContainer" class="pdf-container">
            <!-- The canvas elements will be added here automatically by the script -->
        </div>



    </div>
</template>
<script>
import { ref, onMounted, nextTick } from 'vue';
//import { getDocument } from 'pdfjs-dist';
//import pdfJS from 'pdfjs-dist';
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.min';
import * as pdfJS from 'pdfjs-dist/build/pdf';


/* eslint-disable */
export default {
    data() {
        return {
            //totalPages: 0,
            
            
        };
    },
    props: ['src'],
    components: {

    },
    setup(props) {
        //const pdfCanvas = ref(null);
        const pdfDoc = ref(null);
        const pdfCanvasContainer = ref(null);
        const totalPages = ref(0);
        const gotoPageNum = ref(1);
        
        const canvases = ref([]);

        pdfJS.GlobalWorkerOptions.workerSrc = pdfjsWorker;
        console.log("work location: ", pdfJS.GlobalWorkerOptions.workerSrc)
        onMounted(async () => {

            const { src } = props;
            //console.log("22222", src)
            //var pdfSrc = "http://localhost:81/static/chapters/java灵魂15问.pdf";
            //var pdfSrc = `${window.localtion.origin}/java灵魂15问.pdf`;
            const CMAP_URL = "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.943/cmaps/";
            let obj = {};
            obj.url = src;
            obj.cMapUrl = CMAP_URL;
            obj.cMapPacked = false;

            pdfDoc.value = await pdfJS.getDocument(obj).promise;
            const numPages = pdfDoc.value.numPages;

            for (let pageNum = 1; pageNum <= numPages; pageNum++) {
                await nextTick(); // 等待 DOM 更新
                const canvas = document.createElement('canvas');
                pdfCanvasContainer.value.appendChild(canvas);
                await renderPage(pdfDoc.value, pageNum, canvas);
                canvases.value.push(canvas);
            }

        
            totalPages.value = numPages;

        });


        async function renderPage(pdfDoc, num, canvas) {
            try {
                const page = await pdfDoc.getPage(num);
                const context = canvas.getContext('2d');
                const scale = 1.3;
                const viewport = page.getViewport(scale);
                var CSS_UNITS = 96.0 / 72.0;
                canvas.height = Math.floor(viewport.height * CSS_UNITS);
                canvas.width = Math.floor(viewport.width * CSS_UNITS);

                const renderContext = {
                    transform: [CSS_UNITS, 0, 0, CSS_UNITS, 0, 0],
                    canvasContext: context,
                    viewport: viewport
                };
                
                await page.render(renderContext).promise;
            } catch (error) {
                // 如果在渲染过程中遇到错误，捕获并处理它们
                console.error(`无法渲染第${num}页：`, error);
            }

        };
        
        const printPdf = () => {
            // 打印PDF文档
            const printWindow = window.open('', '_blank');
            printWindow.document.write('<html><head><title>Print</title></head><body>');
            for (let i = 0; i < totalPages.value; i++) {
                const canvas = canvases.value[i];
                console.log("canvas:", canvas);
                const imgData = canvas.toDataURL();
                const width = canvas.width;
                const height = canvas.height;
                printWindow.document.write(
                    `<img src="${imgData}" width="${width}" height="${height}" style="page-break-after: always;">`
                );
            }
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        };

        const goToPage = () => {
            // 跳转到指定页码
            const pageIndex = Math.max(1, Math.min(totalPages.value, gotoPageNum.value)) - 1;
            const targetY = canvases.value[pageIndex].offsetTop;
            window.scrollTo({ top: targetY, behavior: 'smooth' });
        };
       
        return {
            pdfCanvasContainer,
            pdfDoc,
            totalPages,
            printPdf,
            goToPage,
            gotoPageNum
        };
    },
    methods: {
        navigateToSrc() {

            console.log("src is: ", this.src)
            window.open(this.src, "_blank");
        },
        
    }
};
</script>


<style scoped>

.fixed-navigation {
    position: fixed;
    top: 50;
    left: 400;
    right: 0;
    background-color: #fff; /* 设置背景颜色以防止内容显示在导航栏下方 */
    z-index: 1000; /* 确保导航栏始终在其他元素之上 */
    padding: 10px; /* 添加内边距使其看起来更美观 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影以使其看起来更清晰 */
}

</style>